(function (mui, window, document, undefined) {
    mui.init();
    var get = function (id) {
        return document.getElementById(id);
    };
    var ui = {
        question: get('question'),
        contact: get('contact'),
        imageList: get('image-list'),
        submit: get('submit')
    };
    /*清除表单*/
    ui.clearForm = function () {
        ui.question.value = '';
        ui.contact.value = '';
        ui.imageList.innerHTML = '';
        ui.newPlaceholder();
    };
    /*query all fileinput*/
    ui.getFileInputArray = function () {
        return [].slice.call(ui.imageList.querySelectorAll('input[type="file"]'));
    };
    var imageIndexIdNum = 0;

    ui.newPlaceholder = function (multiple) {
        var fileInputArray = ui.getFileInputArray();
        /*之前添加的清除掉多选, 只能单选替换*/
        var fileInputArrayLength = fileInputArray.length;
        for (var i = 0; i < fileInputArrayLength; i++) {
            fileInputArray[i].removeAttribute("multiple");
        }
        // if (fileInputArray &&
        //     fileInputArray.length > 0 &&
        //     fileInputArray[fileInputArray.length - 1].parentNode.classList.contains('space')) {
        //     return;
        // }
        imageIndexIdNum++;
        var placeholder = document.createElement('div');
        placeholder.setAttribute('class', 'image-item space');
        placeholder.setAttribute('id', 'placeholder-' + imageIndexIdNum);
        /*关闭按钮*/
        var closeButton = document.createElement('div');
        closeButton.setAttribute('class', 'image-close');
        closeButton.innerHTML = 'X';
        closeButton.addEventListener('click', function (event) {
            event.stopPropagation();
            event.cancelBubble = true;
            setTimeout(function () {
                ui.imageList.removeChild(placeholder);
            }, 0);
            return false;
        }, false);

        /*create + */
        var fileInput = document.createElement('input');
        fileInput.setAttribute('type', 'file');
        /*可以选择多图*/
        if (multiple) {
            fileInput.setAttribute('multiple', true);
        }
        fileInput.setAttribute('accept', 'image/*');
        fileInput.setAttribute('id', 'image-' + imageIndexIdNum);
        fileInput.addEventListener('change', function (event) {
            var files = fileInput.files;
            console.log(files[0]);
            var filesLength = files.length;
            var id = fileInput.getAttribute("id");
            /*id 最大的一个Fileinput*/
            var placeholderClicked = id == ('image-' + imageIndexIdNum);
            for (var i = 0; i < filesLength; i++) {
                var placeholder_inner;
                if (i == 0) {
                    placeholder_inner = placeholder;
                } else {
                    placeholder_inner = ui.newPlaceholder();
                }
                /*当点击placeholder ,在最后重新生成一个 placeholder*/
                if (i == filesLength - 1 && placeholderClicked) {
                    ui.newPlaceholder(true);
                }
                var file = files[i];
                if (file) {
                    var reader = new FileReader();
                    var onload_index = 0;
                    reader.onload = function () {
                        //处理 android 4.1 兼容问题
                        var base64 = this.result.split(',')[1];
                        var dataUrl = 'data:image/png;base64,' + base64;
                        var fileInputId = fileInput.getAttribute("id");
                        var idInt = fileInputId.substr(fileInputId.indexOf("-") + 1, fileInputId.length);
                        var placeHolderId = (parseInt(idInt) + onload_index);
                        console.log("onload_index", onload_index++)
                        var placeHolderFindById = document.getElementById("placeholder-" + placeHolderId);
                        placeHolderFindById.style.backgroundImage = 'url(' + dataUrl + ')';
                    }
                    reader.readAsDataURL(file);
                    placeholder_inner.classList.remove('space');
                }
            }
        }, false);
        placeholder.appendChild(closeButton);
        placeholder.appendChild(fileInput);
        ui.imageList.appendChild(placeholder);
        return placeholder;
    };

    ui.newPlaceholder(true);
    /*提交时调用 */
    ui.getFileInputIdArray = function () {
        var fileInputArray = ui.getFileInputArray();
        var idArray = [];
        fileInputArray.forEach(function (fileInput) {
            if (fileInput.value != '') {
                idArray.push(fileInput.getAttribute('id'));
            }
        });
        return idArray;
    };
    /*提交*/
    ui.submit.addEventListener('tap', function (event) {
        console.log("commit")
        var fileInputArray = ui.getFileInputArray();
        console.log(fileInputArray)
        console.log(fileInputArray.length)
        fileInputArray.forEach(function (fileInputId) {
            console.log("fileInputId");
            console.log(fileInputId);
            console.log(fileInputId.value);
            console.log(getFileUrlFn(fileInputId));
            // conn.sendPicture({
            //     fileInputId: fileInputId,
            //     to: CUSTOM_ID,
            //     onFileUploadError: function (error) {
            //         //处理图片上传失败
            //         alert(JSON.stringify(error));
            //         hasError = true;
            //     },
            //     onFileUploadComplete: function (data) {
            //         //处理图片上传成功，如本地消息显示
            //         sendImageCount++;
            //         if (!hasError && sendImageCount >= content.images.length) {
            //             if (callback) callback();
            //         }
            //     }
            // });
        });
        // console.log(browser.version.ios);
        if (ui.question.value == '' ||
            (ui.contact.value != '' &&
                ui.contact.value.search(/^(\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+)|([1-9]\d{4,9})$/) != 0)) {
            return mui.toast('信息填写不符合规范');
        }
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        alert('是否是Android：' + isAndroid);
        alert('是否是iOS：' + isiOS);

        /*plus.nativeUI.showWaiting();
        feedback.send({
            question: ui.question.value,
            contact: ui.contact.value,
            images: ui.getFileInputIdArray()
        }, function () {
            plus.nativeUI.closeWaiting();
            mui.toast('感谢您的建议~');
            ui.clearForm();
            mui.back();
        });*/
    }, false);
})(mui, window, document, undefined);

var getFileUrlFn = function (fileInputId) {
    var uri = {
        url: '',
        filename: '',
        filetype: ''
    };
    if (window.URL && window.URL.createObjectURL) {
        // var fileItems = document.getElementById(fileInputId).files;
        var fileItems = fileInputId.files;
        if (fileItems.length > 0) {
            var u = fileItems.item(0);
            uri.url = window.URL.createObjectURL(u);
            uri.filename = u.name || '';
        }
    } else { // IE
        var u = document.getElementById(fileInputId).value;
        uri.url = u;
        var pos1 = u.lastIndexOf('/');
        var pos2 = u.lastIndexOf('\\');
        var pos = Math.max(pos1, pos2)
        if (pos < 0)
            uri.filename = u;
        else
            uri.filename = u.substring(pos + 1);
    }
    var index = uri.filename.lastIndexOf(".");
    if (index != -1) {
        uri.filetype = uri.filename.substring(index + 1).toLowerCase();
    }
    return uri;
};